import requests
import pickle
import os
import json

# 文件路径
COOKIES_FILE = '../cookies/gkzy_session.pkl'


def login():
    """登录函数"""
    session = requests.Session()
    login_url = 'https://apin.gkzycc.cn/api/auth/login'

    # 准备登录数据（需要补充你的实际登录凭证）
    login_data = {
        'account': '19947079679',
        'autoLogin': 'true',
        'channel': 2,
        'code': '0',
        'password': '19947079679',
        'uuid': 'zyccn:CodeKey:eaeb3b62f822433a8eaaef6bf6a7a643'
    }

    headers = {
        'Content-Type': 'application/json',
    }

    # 发送登录请求
    response = session.post(login_url, json=login_data, headers=headers)

    if response.status_code == 200:
        print("登录成功！")
        # 保存cookies到文件
        with open(COOKIES_FILE, 'wb') as f:
            pickle.dump(session.cookies, f)
        return session
    else:
        raise Exception(f"登录失败，状态码: {response.status_code}")


def get_session():
    """获取会话，优先使用保存的cookies"""
    if os.path.exists(COOKIES_FILE):
        try:
            # 尝试加载保存的cookies
            session = requests.Session()
            with open(COOKIES_FILE, 'rb') as f:
                session.cookies.update(pickle.load(f))

            # 测试cookies是否仍然有效
            test_url = 'https://wl.gkzycc.cn/data/collegeList'
            test_response = session.get(test_url)
            if test_response.status_code == 200:
                print("检测到有效cookies，无需重新登录")
                return session
        except Exception as e:
            print(f"加载cookies失败: {e}")

    # 如果没有保存的cookies或已失效，重新登录
    print("未检测到有效cookies，正在重新登录...")
    return login()


# 主程序
if __name__ == "__main__":
    try:
        # 获取会话（自动判断是否需要登录）
        session = get_session()

        headers = {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36',
            'Referer': 'https://wl.gkzycc.cn/',
            'Origin': 'https://wl.gkzycc.cn',
            # 如果请求需要授权，可以添加 Authorization 头
            # 'Authorization': 'Bearer xxx'
        }

        # API参数配置
        payload = {
            'size': 10,
            'page': 1,
            'sort': 'sorted,DESC'
        }

        api_url = 'https://apin.gkzycc.cn/api/college/page'
        response = session.post(api_url, headers=headers, data=json.dumps(payload))

        if response.status_code == 200:
            data = response.json()
            print('data', data)
            colleges = data.get('data', {}).get('records', [])

            for college in colleges:
                print(f"大学名称: {college.get('name')}")
                print(f"标签: {college.get('tags')}")
                print(f"省份: {college.get('province')}")
                print(f"类型: {college.get('type')}")
                print(f"主管部门: {college.get('department')}")
                print("-" * 50)

            with open('colleges.json', 'w', encoding='utf-8') as f:
                json.dump(colleges, f, ensure_ascii=False, indent=2)
            print("数据已保存到 colleges.json")
        else:
            print(f"请求失败，状态码: {response.status_code}")
            print("响应内容:", response.text)

    except Exception as e:
        print(f"发生错误: {e}")
        # 如果出错，删除可能无效的cookies文件
        if os.path.exists(COOKIES_FILE):
            os.remove(COOKIES_FILE)
